// 1. React核心库
import React, { useState, useEffect, useRef } from 'react';

// 2. UI组件库 - 按字母顺序
import { Button, Input, List, Avatar, Space, message, Spin, Select, Modal, Popconfirm, Tooltip, Dropdown } from 'antd';

// 2.5. Markdown渲染组件
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';

// 2.6. 自定义滚动组件
import { Scrollbars } from 'react-custom-scrollbars-2';

// 3. 图标库
import { 
  SendOutlined, 
  UserOutlined, 
  RobotOutlined, 
  StarOutlined, 
  StarFilled, 
  FileTextOutlined,
  EditOutlined,
  DeleteOutlined,
  CheckOutlined,
  CloseOutlined,
  CopyOutlined,
  DownOutlined,
  MenuOutlined,
  VerticalAlignTopOutlined
} from '@ant-design/icons';

// 5. 工具库
import { useCallback } from 'react';
import dayjs from 'dayjs';

// 7. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';
import { ChatWebSocketService } from '@/services/websocket/chatWebSocketService';

// 8. 生成的类型定义 (必须使用，禁止手工定义)
import type { 
  AIConversation, 
  AIMessage, 
  AIRole, 
  AIModel, 
  MessageTemplate 
} from '@/services/generated';

const { TextArea } = Input;

interface ChatInterfaceProps {
  conversation: AIConversation | null;
  selectedTemplate?: string;
  onTemplateUsed?: () => void;
  onConversationUpdate?: (conversation: AIConversation) => void;
  onTemplateSelect?: (template: MessageTemplate) => void;
}

const ChatInterface: React.FC<ChatInterfaceProps> = ({ 
  conversation, 
  selectedTemplate = '', 
  onTemplateUsed,
  onConversationUpdate,
  onTemplateSelect 
}) => {
  const [messages, setMessages] = useState<AIMessage[]>([]);
  const [inputValue, setInputValue] = useState('');
  const [messagesLoading, setMessagesLoading] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const scrollbarsRef = useRef<Scrollbars>(null);
  const streamingContentRef = useRef<string>(''); // 使用ref保存流式内容的最新值
  
  // 控制栏相关状态
  const [roles, setRoles] = useState<AIRole[]>([]);
  const [models, setModels] = useState<AIModel[]>([]);
  const [templates, setTemplates] = useState<MessageTemplate[]>([]);
  const [isFavorited, setIsFavorited] = useState(false);
  const [templatesModalVisible, setTemplatesModalVisible] = useState(false);
  const [controlLoading, setControlLoading] = useState(false);

  // 编辑消息相关状态
  const [editingMessageId, setEditingMessageId] = useState<number | null>(null);
  const [editingContent, setEditingContent] = useState('');
  const [editLoading, setEditLoading] = useState(false);
  const [deleteLoading, setDeleteLoading] = useState<number[]>([]);

  // WebSocket流式对话相关状态
  const [wsService, setWsService] = useState<ChatWebSocketService | null>(null);
  const [isStreaming, setIsStreaming] = useState(false);
  const [currentStreamId, setCurrentStreamId] = useState<string | null>(null);
  const [streamingContent, setStreamingContent] = useState('');
  const [wsConnected, setWsConnected] = useState(false);

  // 发送消息状态
  const [sendLoading, setSendLoading] = useState(false);
  
  // 智能滚动相关状态
  const [isUserAtBottom, setIsUserAtBottom] = useState(true);
  const [showScrollToBottom, setShowScrollToBottom] = useState(false);
  const [userManuallyScrolled, setUserManuallyScrolled] = useState(false);
  const [isUserScrolling, setIsUserScrolling] = useState(false);

  // 右键菜单相关状态
  const [contextMenuMessage, setContextMenuMessage] = useState<AIMessage | null>(null);

  // 处理滚动事件
  const handleScroll = useCallback((values: any) => {
    // onScrollFrame 提供的参数格式: { top, left, clientWidth, clientHeight, scrollWidth, scrollHeight, scrollTop, scrollLeft }
    const { top, scrollTop, scrollHeight, clientHeight } = values;
    
    // 计算距离底部的实际像素距离，更精确地判断
    const distanceFromBottom = scrollHeight - scrollTop - clientHeight;
    
    // 更严格的底部判断：距离底部10px以内才认为在底部
    const isNearBottom = distanceFromBottom <= 10;
    // 进度值也要更严格：99.8%以上才认为在底部
    const isProgressAtBottom = top >= 0.998;
    
    const finalIsAtBottom = isNearBottom && isProgressAtBottom;
    
    // 调试日志
    console.log('滚动检测:', {
      top: top.toFixed(3),
      distanceFromBottom: distanceFromBottom.toFixed(2),
      isNearBottom,
      isProgressAtBottom,
      finalIsAtBottom,
      userManuallyScrolled,
      isStreaming
    });
    
    setIsUserAtBottom(finalIsAtBottom);
    setShowScrollToBottom(!finalIsAtBottom && (messages.length > 0 || isStreaming));
    
    // 如果用户滚动到不在严格底部，标记为手动滚动
    if (!finalIsAtBottom && isStreaming) {
      if (!userManuallyScrolled) {
        setUserManuallyScrolled(true);
        console.log('用户离开底部: 设置手动滚动为true');
      }
    }
    // 如果用户滚动回到严格底部，重置手动滚动标记
    else if (finalIsAtBottom && userManuallyScrolled) {
      setUserManuallyScrolled(false);
      console.log('用户回到底部: 重置手动滚动标记');
    }
  }, [messages.length, isStreaming, userManuallyScrolled]);

  // 处理滚动开始事件
  const handleScrollStart = useCallback(() => {
    console.log('用户开始滚动');
    setIsUserScrolling(true);
    // 用户一旦开始滚动，就标记为手动滚动
    if (isStreaming) {
      setUserManuallyScrolled(true);
      console.log('流式输出中用户开始滚动，标记为手动滚动');
    }
  }, [isStreaming]);

  // 处理滚动结束事件
  const handleScrollStop = useCallback(() => {
    console.log('用户结束滚动');
    setIsUserScrolling(false);
  }, []);
  
  // 智能滚动到底部
  const smartScrollToBottom = useCallback(() => {
    const scrollbars = scrollbarsRef.current;
    if (!scrollbars) return;
    
    // 调试日志
    console.log('智能滚动检查:', {
      isStreaming,
      isUserAtBottom,
      userManuallyScrolled,
      isUserScrolling,
      shouldScroll: isStreaming ? (isUserAtBottom && !userManuallyScrolled && !isUserScrolling) : isUserAtBottom
    });
    
    // 更严格的自动滚动条件
    if (isStreaming) {
      // 流式生成时：必须同时满足以下所有条件才自动滚动
      // 1. 用户当前在底部附近
      // 2. 用户没有手动滚动过
      // 3. 用户当前没在滚动操作中
      if (isUserAtBottom && !userManuallyScrolled && !isUserScrolling) {
        console.log('执行自动滚动 - 流式模式');
        // 使用 requestAnimationFrame 确保DOM更新完成后再滚动
        requestAnimationFrame(() => {
          if (scrollbarsRef.current && isUserAtBottom && !userManuallyScrolled && !isUserScrolling) {
            scrollbarsRef.current.scrollToBottom();
          }
        });
      } else {
        console.log('跳过自动滚动 - 流式模式，条件不满足');
      }
    } else {
      // 非流式生成时：只有用户在底部时才自动滚动
      if (isUserAtBottom) {
        console.log('执行自动滚动 - 非流式模式');
        scrollbars.scrollToBottom();
      } else {
        console.log('跳过自动滚动 - 非流式模式，用户不在底部');
      }
    }
  }, [isUserAtBottom, isStreaming, userManuallyScrolled, isUserScrolling]);
  
  // 强制滚动到底部（点击按钮时使用）
  const forceScrollToBottom = useCallback(() => {
    const scrollbars = scrollbarsRef.current;
    if (scrollbars) {
      scrollbars.scrollToBottom();
      setIsUserAtBottom(true);
      setShowScrollToBottom(false);
      setUserManuallyScrolled(false); // 重置手动滚动标记
    }
  }, []);

  // 获取消息列表
  const fetchMessages = async () => {
    if (!conversation?.id) return;
    
    try {
      setMessagesLoading(true);
      await autoLoginInDev();
      const response = await apiClients.aiChat.aiChatMessagesList({
        conversation: conversation.id,
        pageSize: 100,
      });
      setMessages(response.data?.items || []);
    } catch (error) {
      console.error('获取消息列表失败:', error);
      message.error('获取消息列表失败');
    } finally {
      setMessagesLoading(false);
    }
  }; 

  // 发送消息
  const sendMessage = async (content: string) => {
    if (!conversation?.id) return;
    
    try {
      setSendLoading(true);
      await autoLoginInDev();
      const response = await apiClients.aiChat.aiChatConversationsSendMessageCreate({
        id: String(conversation.id),
        messageSendRequest: {
          content,
          include_context: true,
          context_limit: 10,
        },
      });
      
      // 重新获取消息列表
      await fetchMessages();
      setInputValue('');
      message.success('消息发送成功');
      return response;
    } catch (error) {
      message.error('消息发送失败');
      console.error('发送消息失败:', error);
    } finally {
      setSendLoading(false);
    }
  };

  // WebSocket相关方法
  const initWebSocket = () => {
    if (!conversation?.id) return;

    const config = {
      conversationId: conversation.id,
      onConnect: () => {
        console.log('WebSocket连接成功');
        setWsConnected(true);
      },
      onDisconnect: () => {
        console.log('WebSocket连接断开');
        setWsConnected(false);
      },
      onError: (error: Event) => {
        console.error('WebSocket连接错误:', error);
        setWsConnected(false);
      },
      onStreamStart: (data: any) => {
        console.log('流式对话开始:', data);
        setCurrentStreamId(data.stream_id);
        setStreamingContent('');
        streamingContentRef.current = '';
        setUserManuallyScrolled(false); // 重置手动滚动标记
      },
      onStreamChunk: (data: any) => {
        console.log('收到流式内容:', data);
        setCurrentStreamId(data.stream_id);
        setStreamingContent(data.content);
        streamingContentRef.current = data.content; // 保存到ref中
        
        // 添加防抖，避免频繁滚动，且只在满足条件时滚动
        setTimeout(() => {
          // 严格检查所有条件，确保用户没有在此期间手动滚动
          if (isUserAtBottom && !userManuallyScrolled && !isUserScrolling) {
            smartScrollToBottom();
          }
        }, 50); // 50ms 防抖
      },
      onStreamComplete: (data: any) => {
        console.log('流式对话完成:', data);
        
        // 使用ref中保存的最新内容作为最终AI消息
        const finalContent = streamingContentRef.current;
        if (finalContent) {
          const aiMessage: AIMessage = {
            id: data.message_id || Date.now() + 1,
            content: finalContent,
            is_user_message: false,
            created_at: new Date(),
            updated_at: new Date(),
            conversation: conversation?.id || 0,
            ai_role_name: '',
            context_position: '',
            estimated_tokens: '',
            token_count: 0,
            ai_role: null,
            created_by: null,
            updated_by: null,
          };
          
          setMessages(prevMessages => [...prevMessages, aiMessage]);
        }
        
        setIsStreaming(false);
        setCurrentStreamId(null);
        setStreamingContent('');
        streamingContentRef.current = '';
        setUserManuallyScrolled(false); // 重置手动滚动标记
      },
      onStreamError: (data: any) => {
        console.error('流式对话错误:', data);
        message.error(`流式对话出错: ${data.message}`);
        setIsStreaming(false);
        setCurrentStreamId(null);
        setStreamingContent('');
        streamingContentRef.current = '';
        setUserManuallyScrolled(false); // 重置手动滚动标记
      },
      onStreamStopped: (data: any) => {
        console.log('流式对话已停止:', data);
        setIsStreaming(false);
        setCurrentStreamId(null);
        setStreamingContent('');
        streamingContentRef.current = '';
        setUserManuallyScrolled(false); // 重置手动滚动标记
        message.info('流式对话已停止');
      },
    };

    const ws = new ChatWebSocketService(config);
    ws.connect();
    setWsService(ws);
  };

  const cleanupWebSocket = () => {
    if (wsService) {
      wsService.disconnect();
      setWsService(null);
      setWsConnected(false);
      setIsStreaming(false);
      setCurrentStreamId(null);
      setStreamingContent('');
      streamingContentRef.current = '';
      setUserManuallyScrolled(false); // 重置手动滚动标记
    }
  };

  // 使用WebSocket发送流式消息
  const sendStreamMessage = async (content: string) => {
    if (!wsService || !wsService.isConnected) {
      message.error('WebSocket未连接，使用普通发送方式');
      sendMessage(content);
      return;
    }

    if (isStreaming) {
      message.warning('正在进行流式对话，请稍候');
      return;
    }

    // 显示发送中状态
    setSendLoading(true);

    try {
      // 先立即添加用户消息到界面
      const tempUserMessage: AIMessage = {
        id: Date.now(),
        content: content,
        is_user_message: true,
        created_at: new Date(),
        updated_at: new Date(),
        conversation: conversation?.id || 0,
        ai_role_name: '',
        context_position: '',
        estimated_tokens: '',
        token_count: 0,
        ai_role: null,
        created_by: null,
        updated_by: null,
      };

      setMessages(prevMessages => [...prevMessages, tempUserMessage]);
      setInputValue('');

      // 获取当前选择的模型和角色
      const selectedModel = models.find(m => m.id === conversation?.ai_model);
      const selectedRole = roles.find(r => r.id === conversation?.ai_role);

      setIsStreaming(true);
      setStreamingContent('');
      streamingContentRef.current = '';
      setUserManuallyScrolled(false); // 重置手动滚动标记

      wsService.startStream(
        content,
        selectedModel?.name,
        selectedRole?.name
      );
    } finally {
      // 发送完成后取消发送中状态
      setSendLoading(false);
    }
  };

  // 获取角色列表
  const fetchRoles = async () => {
    try {
      await autoLoginInDev();
      const response = await apiClients.aiChat.aiChatRolesList({
        pageSize: 100,
      });
      setRoles(response.data?.items || []);
    } catch (error) {
      console.error('获取角色列表失败:', error);
    }
  };

  // 获取模型列表
  const fetchModels = async () => {
    try {
      await autoLoginInDev();
      const response = await apiClients.aiChat.aiChatModelsList({
        pageSize: 100,
      });
      setModels(response.data?.items || []);
    } catch (error) {
      console.error('获取模型列表失败:', error);
    }
  };

  // 获取消息模板列表
  const fetchTemplates = async () => {
    try {
      await autoLoginInDev();
      const response = await apiClients.aiChat.aiChatTemplatesList({
        pageSize: 100,
      });
      setTemplates(response.data?.items || []);
    } catch (error) {
      console.error('获取模板列表失败:', error);
    }
  };

  // 检查对话是否已收藏
  const checkConversationFavorited = async () => {
    if (!conversation?.id) return;
    
    try {
      await autoLoginInDev();
      const response = await apiClients.aiChat.aiChatFavoritesList({
        pageSize: 100,
      });
      
      const favorited = response.data?.items?.some(
        favorite => favorite.conversation === conversation.id
      );
      setIsFavorited(!!favorited);
    } catch (error) {
      console.error('检查收藏状态失败:', error);
    }
  };

  // 处理发送消息
  const handleSend = () => {
    if (!inputValue.trim()) {
      message.warning('请输入消息内容');
      return;
    }
    
    // 优先使用WebSocket流式发送
    if (wsConnected && wsService?.isConnected) {
      sendStreamMessage(inputValue.trim());
    } else {
      sendMessage(inputValue.trim());
    }
  };

  // 处理回车发送
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  // 关闭右键菜单
  const closeContextMenu = () => {
    setContextMenuMessage(null);
  };

  // 初始化滚动位置检查
  useEffect(() => {
    const scrollbars = scrollbarsRef.current;
    if (scrollbars) {
      // 初始时认为用户在底部
      setIsUserAtBottom(true);
      setUserManuallyScrolled(false);
    }
  }, []);

  
  // 初始化控制栏数据
  useEffect(() => {
    fetchRoles();
    fetchModels();
    fetchTemplates();
  }, []);

  // 监听对话变化，初始化消息和检查收藏状态
  useEffect(() => {
    if (conversation?.id) {
      fetchMessages();
      checkConversationFavorited();
      initWebSocket();
    } else {
      cleanupWebSocket();
    }
  }, [conversation?.id]);

  // 组件卸载时清理WebSocket
  useEffect(() => {
    return () => {
      cleanupWebSocket();
    };
  }, []);

  useEffect(() => {
    smartScrollToBottom();
  }, [messages, streamingContent, smartScrollToBottom]);

  // 更新对话角色
  const handleRoleChange = async (roleId: number) => {
    if (!conversation?.id || !onConversationUpdate) {
      message.error('缺少必要参数，无法切换角色');
      return;
    }

    try {
      setControlLoading(true);
      
      await autoLoginInDev();
      const response = await apiClients.aiChat.aiChatConversationsUpdate({
        id: String(conversation.id),
        aIConversationRequest: {
          title: conversation.title,
          status: conversation.status,
          ai_model: conversation.ai_model,
          ai_role: roleId,
        },
      });
      onConversationUpdate(response.data);
      message.success('角色切换成功');
    } catch (error) {
      message.error(`角色切换失败: ${error instanceof Error ? error.message : '未知错误'}`);
    } finally {
      setControlLoading(false);
    }
  };

  // 更新对话模型
  const handleModelChange = async (modelId: number) => {
    if (!conversation?.id || !onConversationUpdate) {
      message.error('缺少必要参数，无法切换模型');
      return;
    }

    try {
      setControlLoading(true);
      
      await autoLoginInDev();
      const response = await apiClients.aiChat.aiChatConversationsUpdate({
        id: String(conversation.id),
        aIConversationRequest: {
          title: conversation.title,
          status: conversation.status,
          ai_model: modelId,
          ai_role: conversation.ai_role,
        },
      });
      onConversationUpdate(response.data);
      message.success('模型切换成功');
    } catch (error) {
      message.error(`模型切换失败: ${error instanceof Error ? error.message : '未知错误'}`);
    } finally {
      setControlLoading(false);
    }
  };

  // 收藏/取消收藏对话
  const handleToggleFavorite = async () => {
    if (!conversation?.id) return;

    try {
      setControlLoading(true);
      await autoLoginInDev();
      
      if (isFavorited) {
        // 取消收藏 - 需要先找到收藏记录ID
        const favoritesResponse = await apiClients.aiChat.aiChatFavoritesList({
          pageSize: 100,
        });
        const favoriteRecord = favoritesResponse.data?.items?.find(
          favorite => favorite.conversation === conversation.id
        );
        
        if (favoriteRecord?.id) {
          await apiClients.aiChat.aiChatFavoritesDestroy({
            id: String(favoriteRecord.id),
          });
          setIsFavorited(false);
          message.success('已取消收藏');
        }
      } else {
        // 添加收藏
        await apiClients.aiChat.aiChatFavoritesCreate({
          userFavoriteRequest: {
            title: conversation.title || '对话收藏',
            conversation: conversation.id,
            message: null,
            note: `收藏的对话: ${conversation.title}`,
          },
        });
        setIsFavorited(true);
        message.success('已收藏对话');
      }
    } catch (error) {
      message.error(isFavorited ? '取消收藏失败' : '收藏失败');
    } finally {
      setControlLoading(false);
    }
  };

  // 开始编辑消息
  const startEditMessage = (messageItem: AIMessage) => {
    if (!messageItem.is_user_message) {
      message.warning('只能编辑用户消息');
      return;
    }
    setEditingMessageId(messageItem.id);
    setEditingContent(messageItem.content);
  };

  // 取消编辑
  const cancelEditMessage = () => {
    setEditingMessageId(null);
    setEditingContent('');
  };

  // 保存编辑的消息并重发
  const saveEditMessage = async (messageId: number) => {
    if (!editingContent.trim()) {
      message.warning('消息内容不能为空');
      return;
    }

    try {
      setEditLoading(true);
      await autoLoginInDev();

      // 1. 更新消息内容
      await apiClients.aiChat.aiChatMessagesPartialUpdate({
        id: String(messageId),
        patchedAIMessageRequest: {
          content: editingContent.trim(),
        },
      });

      // 2. 取消编辑状态
      cancelEditMessage();

      // 3. 重新发送消息获取AI回复
      await sendMessage(editingContent.trim());
      
      message.success('消息已更新并重新发送');
    } catch (error) {
      message.error('消息编辑失败');
    } finally {
      setEditLoading(false);
    }
  };

  // 删除消息
  const deleteMessage = async (messageId: number) => {
    try {
      setDeleteLoading(prev => [...prev, messageId]);
      await autoLoginInDev();
      
      await apiClients.aiChat.aiChatMessagesDestroy({
        id: String(messageId),
      });
      
      // 重新获取消息列表
      await fetchMessages();
      message.success('消息已删除');
    } catch (error) {
      message.error('消息删除失败');
    } finally {
      setDeleteLoading(prev => prev.filter(id => id !== messageId));
    }
  };

  // 复制消息内容
  const copyMessage = async (content: string) => {
    try {
      await navigator.clipboard.writeText(content);
      message.success('已复制到剪贴板');
    } catch (error) {
      // 如果系统不支持clipboard API，提示手动复制
      message.error('复制失败，请手动复制');
      console.error('复制失败:', error);
    }
  };

  // 复制所有消息内容
  const copyAllMessages = async () => {
    try {
      const allContent = messages.map(msg => {
        const role = msg.is_user_message ? '用户' : 'AI';
        const time = dayjs(msg.created_at).format('HH:mm');
        return `[${time}] ${role}: ${msg.content}`;
      }).join('\n\n');
      
      await navigator.clipboard.writeText(allContent);
      message.success('已复制所有消息到剪贴板');
    } catch (error) {
      message.error('复制失败，请手动复制');
      console.error('复制失败:', error);
    }
  };

  // 滚动到消息行首
  const scrollToMessageTop = (messageId: number) => {
    const messageElement = document.querySelector(`[data-message-id="${messageId}"]`);
    if (messageElement) {
      messageElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  };

  // 停止流式对话
  const stopStreaming = () => {
    if (wsService && currentStreamId) {
      wsService.stopStream(currentStreamId);
    }
  };


  // 右键菜单项
  const getContextMenuItems = (messageItem: AIMessage) => [
    {
      key: 'copy-message',
      label: '复制消息',
      icon: <CopyOutlined />,
      onClick: () => {
        copyMessage(messageItem.content);
      },
    },
    {
      key: 'copy-all',
      label: '复制全部消息',
      icon: <MenuOutlined />,
      onClick: copyAllMessages,
    },
    {
      key: 'scroll-to-top',
      label: '回到消息行首',
      icon: <VerticalAlignTopOutlined />,
      onClick: () => scrollToMessageTop(messageItem.id),
    },
    messageItem.is_user_message && {
      key: 'edit-message',
      label: '编辑并重发',
      icon: <EditOutlined />,
      onClick: () => {
        startEditMessage(messageItem);
      },
    },
    {
      type: 'divider',
    },
    {
      key: 'delete-message',
      label: '删除消息',
      icon: <DeleteOutlined />,
      danger: true,
      onClick: () => {
        deleteMessage(messageItem.id);
      },
    },
  ].filter(Boolean);

  // 监听模板选择
  useEffect(() => {
    if (selectedTemplate && selectedTemplate !== inputValue) {
      setInputValue(selectedTemplate);
      onTemplateUsed?.();
    }
  }, [selectedTemplate, inputValue, onTemplateUsed]);

  if (!conversation) {
    return <div>请选择一个对话</div>;
  }

  return (
    <div style={{ height: '600px', display: 'flex', flexDirection: 'column' }}>
      {/* 消息列表 */}
      <div style={{ flex: 1, backgroundColor: '#fafafa', position: 'relative' }}>
        <Scrollbars
          ref={scrollbarsRef}
          onScrollFrame={handleScroll}
          onScrollStart={handleScrollStart}
          onScrollStop={handleScrollStop}
          autoHide
          autoHideTimeout={1000}
          autoHideDuration={200}
          style={{ height: '100%' }}
          renderThumbVertical={(props) => (
            <div {...props} style={{ backgroundColor: '#d9d9d9', borderRadius: '4px' }} />
          )}
        >
          <div style={{ padding: '16px' }}>
        <Spin spinning={messagesLoading}>
          <List
            dataSource={messages}
            renderItem={(message) => (
              <Dropdown 
                menu={{ items: getContextMenuItems(message) }} 
                trigger={['contextMenu']}
              >
                <List.Item
                  style={{
                    border: 'none',
                    padding: '8px 0',
                    justifyContent: message.is_user_message ? 'flex-end' : 'flex-start',
                  }}
                  data-message-id={message.id}
                >
                <div
                  style={{
                    maxWidth: '70%',
                    display: 'flex',
                    flexDirection: message.is_user_message ? 'row-reverse' : 'row',
                    alignItems: 'flex-start',
                    gap: '8px',
                  }}
                >
                  <Avatar
                    icon={message.is_user_message ? <UserOutlined /> : <RobotOutlined />}
                    style={{
                      backgroundColor: message.is_user_message ? '#1890ff' : '#52c41a',
                    }}
                  />
                  <div
                    style={{
                      backgroundColor: message.is_user_message ? '#1890ff' : '#fff',
                      color: message.is_user_message ? '#fff' : '#000',
                      padding: '12px 16px',
                      borderRadius: '12px',
                      boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
                    }}
                  >
                    <div style={{ wordBreak: 'break-word' }}>
                      {message.is_user_message ? (
                        editingMessageId === message.id ? (
                          // 编辑模式
                          <div style={{ width: '100%' }}>
                            <Input.TextArea
                              value={editingContent}
                              onChange={(e) => setEditingContent(e.target.value)}
                              autoSize={{ minRows: 2, maxRows: 6 }}
                              style={{ 
                                marginBottom: '8px',
                                borderColor: '#1890ff',
                                backgroundColor: 'rgba(255,255,255,0.9)'
                              }}
                            />
                            <Space>
                              <Button
                                size="small"
                                type="primary"
                                icon={<CheckOutlined />}
                                loading={editLoading}
                                onClick={() => saveEditMessage(message.id)}
                              >
                                保存并重发
                              </Button>
                              <Button
                                size="small"
                                icon={<CloseOutlined />}
                                onClick={cancelEditMessage}
                                disabled={editLoading}
                              >
                                取消
                              </Button>
                            </Space>
                          </div>
                        ) : (
                          // 普通显示模式
                          <div style={{ whiteSpace: 'pre-wrap' }}>
                            {message.content}
                          </div>
                        )
                      ) : (
                        <ReactMarkdown
                          remarkPlugins={[remarkGfm]}
                          components={{
                            p: ({ children }) => <div style={{ margin: '8px 0' }}>{children}</div>,
                            code: ({ children, className }) => (
                              <code
                                className={className}
                                style={{
                                  backgroundColor: '#f5f5f5',
                                  padding: '2px 4px',
                                  borderRadius: '3px',
                                  fontSize: '0.9em',
                                }}
                              >
                                {children}
                              </code>
                            ),
                            pre: ({ children }) => (
                              <pre
                                style={{
                                  backgroundColor: '#f5f5f5',
                                  padding: '12px',
                                  borderRadius: '6px',
                                  overflow: 'auto',
                                  fontSize: '0.9em',
                                }}
                              >
                                {children}
                              </pre>
                            ),
                            table: ({ children }) => (
                              <table
                                style={{
                                  borderCollapse: 'collapse',
                                  width: '100%',
                                  margin: '12px 0',
                                  fontSize: '0.9em',
                                }}
                              >
                                {children}
                              </table>
                            ),
                            thead: ({ children }) => (
                              <thead style={{ backgroundColor: '#f5f5f5' }}>
                                {children}
                              </thead>
                            ),
                            tbody: ({ children }) => (
                              <tbody>{children}</tbody>
                            ),
                            tr: ({ children }) => (
                              <tr style={{ borderBottom: '1px solid #e8e8e8' }}>
                                {children}
                              </tr>
                            ),
                            th: ({ children }) => (
                              <th
                                style={{
                                  border: '1px solid #d9d9d9',
                                  padding: '8px 12px',
                                  textAlign: 'left',
                                  fontWeight: 'bold',
                                }}
                              >
                                {children}
                              </th>
                            ),
                            td: ({ children }) => (
                              <td
                                style={{
                                  border: '1px solid #d9d9d9',
                                  padding: '8px 12px',
                                }}
                              >
                                {children}
                              </td>
                            ),
                          }}
                        >
                          {message.content}
                        </ReactMarkdown>
                      )}
                    </div>
                    <div
                      style={{
                        fontSize: '12px',
                        opacity: 0.7,
                        marginTop: '4px',
                        textAlign: message.is_user_message ? 'right' : 'left',
                        display: 'flex',
                        justifyContent: message.is_user_message ? 'flex-end' : 'space-between',
                        alignItems: 'center',
                        gap: '8px',
                      }}
                    >
                      <span>{dayjs(message.created_at).format('HH:mm')}</span>
                      
                      {/* 用户消息显示操作按钮 */}
                      {message.is_user_message && editingMessageId !== message.id && (
                        <Space size="small">
                          <Tooltip title="复制消息">
                            <Button
                              type="text"
                              size="small"
                              icon={<CopyOutlined />}
                              onClick={() => copyMessage(message.content)}
                              style={{ 
                                color: 'rgba(255,255,255,0.8)',
                                border: 'none'
                              }}
                            />
                          </Tooltip>
                          <Tooltip title="编辑并重发">
                            <Button
                              type="text"
                              size="small"
                              icon={<EditOutlined />}
                              onClick={() => startEditMessage(message)}
                              style={{ 
                                color: 'rgba(255,255,255,0.8)',
                                border: 'none'
                              }}
                            />
                          </Tooltip>
                          <Popconfirm
                            title="确认删除这条消息吗？"
                            onConfirm={() => deleteMessage(message.id)}
                            okText="确认"
                            cancelText="取消"
                          >
                            <Tooltip title="删除消息">
                              <Button
                                type="text"
                                size="small"
                                icon={<DeleteOutlined />}
                                loading={deleteLoading.includes(message.id)}
                                style={{ 
                                  color: 'rgba(255,255,255,0.8)',
                                  border: 'none'
                                }}
                              />
                            </Tooltip>
                          </Popconfirm>
                        </Space>
                      )}
                      
                      {/* AI消息显示操作按钮 */}
                      {!message.is_user_message && (
                        <Space size="small">
                          <Tooltip title="复制AI回复">
                            <Button
                              type="text"
                              size="small"
                              icon={<CopyOutlined />}
                              onClick={() => copyMessage(message.content)}
                              style={{ 
                                color: 'rgba(0,0,0,0.3)',
                                border: 'none'
                              }}
                            />
                          </Tooltip>
                          <Popconfirm
                            title="确认删除这条AI回复吗？"
                            onConfirm={() => deleteMessage(message.id)}
                            okText="确认"
                            cancelText="取消"
                          >
                            <Tooltip title="删除AI回复">
                              <Button
                                type="text"
                                size="small"
                                icon={<DeleteOutlined />}
                                loading={deleteLoading.includes(message.id)}
                                style={{ 
                                  color: 'rgba(0,0,0,0.3)',
                                  border: 'none'
                                }}
                              />
                            </Tooltip>
                          </Popconfirm>
                        </Space>
                      )}
                    </div>
                  </div>
                </div>
                </List.Item>
              </Dropdown>
            )}
          />
          
          {/* 流式内容显示 */}
          {isStreaming && streamingContent && (
            <div
              style={{
                padding: '8px 0',
                display: 'flex',
                justifyContent: 'flex-start',
              }}
            >
              <div
                style={{
                  maxWidth: '70%',
                  display: 'flex',
                  alignItems: 'flex-start',
                  gap: '8px',
                }}
              >
                <Avatar
                  icon={<RobotOutlined />}
                  style={{
                    backgroundColor: '#52c41a',
                  }}
                />
                <div
                  style={{
                    backgroundColor: '#fff',
                    color: '#000',
                    padding: '12px 16px',
                    borderRadius: '12px',
                    boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
                    border: '2px solid #52c41a',
                    position: 'relative',
                  }}
                >
                  <div style={{ wordBreak: 'break-word' }}>
                    <ReactMarkdown
                      remarkPlugins={[remarkGfm]}
                      components={{
                        p: ({ children }) => <div style={{ margin: '8px 0' }}>{children}</div>,
                        code: ({ children, className }) => (
                          <code
                            className={className}
                            style={{
                              backgroundColor: '#f5f5f5',
                              padding: '2px 4px',
                              borderRadius: '3px',
                              fontSize: '0.9em',
                            }}
                          >
                            {children}
                          </code>
                        ),
                        pre: ({ children }) => (
                          <pre
                            style={{
                              backgroundColor: '#f5f5f5',
                              padding: '12px',
                              borderRadius: '6px',
                              overflow: 'auto',
                              fontSize: '0.9em',
                            }}
                          >
                            {children}
                          </pre>
                        ),
                      }}
                    >
                      {streamingContent}
                    </ReactMarkdown>
                  </div>
                  <div
                    style={{
                      fontSize: '12px',
                      opacity: 0.7,
                      marginTop: '4px',
                      display: 'flex',
                      alignItems: 'center',
                      gap: '8px',
                    }}
                  >
                    <span>正在生成中...</span>
                    <div
                      style={{
                        width: '8px',
                        height: '8px',
                        backgroundColor: '#52c41a',
                        borderRadius: '50%',
                        animation: 'pulse 1.5s ease-in-out infinite',
                      }}
                    />
                    {currentStreamId && (
                      <Button
                        type="text"
                        size="small"
                        onClick={stopStreaming}
                        style={{ 
                          color: '#999',
                          fontSize: '10px',
                          padding: '0 4px',
                          height: '20px',
                        }}
                      >
                        停止
                      </Button>
                    )}
                  </div>
                  <style>{`
                    @keyframes pulse {
                      0% {
                        opacity: 1;
                      }
                      50% {
                        opacity: 0.5;
                      }
                      100% {
                        opacity: 1;
                      }
                    }
                    @keyframes fadeInUp {
                      0% {
                        opacity: 0;
                        transform: translateY(20px);
                      }
                      100% {
                        opacity: 1;
                        transform: translateY(0);
                      }
                    }
                  `}</style>
                </div>
              </div>
            </div>
          )}
        </Spin>
        
            <div ref={messagesEndRef} />
          </div>
        </Scrollbars>
        
        {/* 滚动到底部按钮 */}
        {showScrollToBottom && (
          <div
            style={{
              position: 'absolute',
              bottom: '20px',
              right: '20px',
              zIndex: 1000,
            }}
          >
            <Button
              type="primary"
              shape="circle"
              size="large"
              icon={<DownOutlined />}
              onClick={forceScrollToBottom}
              style={{
                boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
                animation: 'fadeInUp 0.3s ease-out',
              }}
              title="回到底部"
            />
          </div>
        )}
      </div>

      {/* 输入区域 */}
      <div style={{ backgroundColor: '#fff', borderTop: '1px solid #f0f0f0' }}>
        {/* 控制栏 */}
        <div style={{ 
          padding: '12px 16px', 
          borderBottom: '1px solid #f0f0f0',
          backgroundColor: '#fafafa'
        }}>
          <Space wrap size="middle">
            {/* 角色选择 */}
            <Space size="small">
              <UserOutlined />
              <span>角色:</span>
              <Select
                value={conversation?.ai_role}
                onChange={handleRoleChange}
                loading={controlLoading}
                style={{ width: 120 }}
                placeholder="选择角色"
                allowClear
              >
                {roles.map(role => (
                  <Select.Option key={role.id} value={role.id}>
                    {role.name}
                  </Select.Option>
                ))}
              </Select>
            </Space>

            {/* 模型选择 */}
            <Space size="small">
              <RobotOutlined />
              <span>模型:</span>
              <Select
                value={conversation?.ai_model}
                onChange={handleModelChange}
                loading={controlLoading}
                style={{ width: 120 }}
                placeholder="选择模型"
                allowClear
              >
                {models.map(model => (
                  <Select.Option key={model.id} value={model.id}>
                    {model.name}
                  </Select.Option>
                ))}
              </Select>
            </Space>

            {/* 对话收藏按钮 */}
            <Button
              type={isFavorited ? "primary" : "default"}
              size="small"
              icon={isFavorited ? <StarFilled /> : <StarOutlined />}
              onClick={handleToggleFavorite}
              loading={controlLoading}
            >
              {isFavorited ? '已收藏' : '收藏对话'}
            </Button>

            {/* 消息模板按钮 */}
            <Button
              size="small"
              icon={<FileTextOutlined />}
              onClick={() => setTemplatesModalVisible(true)}
            >
              消息模板
            </Button>
          </Space>
        </div>
        
        {/* 输入框 */}
        <div style={{ padding: '16px' }}>
          <Space.Compact style={{ width: '100%' }}>
            <TextArea
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              onKeyDown={handleKeyPress}
              placeholder="输入消息内容... (Shift+Enter换行，Enter发送)"
              autoSize={{ minRows: 1, maxRows: 4 }}
              style={{ resize: 'none' }}
            />
            <Button
              type="primary"
              icon={<SendOutlined />}
              loading={sendLoading}
              onClick={handleSend}
              disabled={sendLoading || isStreaming}
              style={{ height: 'auto' }}
            >
              {sendLoading ? '发送中...' : isStreaming ? '生成中...' : '发送'}
            </Button>
          </Space.Compact>
        </div>
      </div>

      {/* 消息模板选择Modal */}
      <Modal
        title="选择消息模板"
        open={templatesModalVisible}
        onCancel={() => setTemplatesModalVisible(false)}
        footer={null}
        width={600}
      >
        <div style={{ maxHeight: 400, overflowY: 'auto' }}>
          {templates.map(template => (
            <div
              key={template.id}
              style={{
                padding: '12px',
                border: '1px solid #f0f0f0',
                borderRadius: '6px',
                marginBottom: '8px',
                cursor: 'pointer',
                transition: 'all 0.2s',
              }}
              onClick={() => {
                if (onTemplateSelect) {
                  onTemplateSelect(template);
                }
                setTemplatesModalVisible(false);
                message.success(`已选择模板: ${template.name}`);
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.backgroundColor = '#f5f5f5';
                e.currentTarget.style.borderColor = '#d9d9d9';
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.backgroundColor = 'white';
                e.currentTarget.style.borderColor = '#f0f0f0';
              }}
            >
              <div style={{ fontWeight: 'bold', marginBottom: '4px' }}>
                {template.name}
              </div>
              <div style={{ 
                color: '#999', 
                fontSize: '12px',
                maxHeight: '60px',
                overflow: 'hidden',
                textOverflow: 'ellipsis'
              }}>
                {template.content}
              </div>
            </div>
          ))}
        </div>
      </Modal>

    </div>
  );
};

export default ChatInterface;
